package com.leetroll.media.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * FTP工具类
 */
@Slf4j
public final class FtpUtil {

    private static final String HOST = "192.168.2.74";
    private static final Integer PORT = 21;
    private static final String USER = "leetroll";
    private static final String PASSWORD = "123654";

    public static final FTPClient ftpClient;

    static {
        ftpClient = new FTPClient();
        //设置传输命令的超时
        ftpClient.setDefaultTimeout(20000);//毫秒
        //设置两个服务连接超时时间
        ftpClient.setConnectTimeout(10000);//毫秒
        try {
            ftpClient.connect(HOST, PORT);
            ftpClient.login(USER, PASSWORD);
        } catch (IOException e) {
            log.error("ftp connect error");
        }
    }

    /**
     * 下载文件
     */
    public static ByteArrayOutputStream download(String path, String fileName) {
        try {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.changeWorkingDirectory(path);
            InputStream stream = ftpClient.retrieveFileStream(fileName);

            if (stream == null) return null;

            //复制流
            ByteArrayOutputStream outputStream = cloneInputStream(stream);

            stream.close();
            ftpClient.completePendingCommand();

            return outputStream;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static ByteArrayOutputStream cloneInputStream(InputStream stream) {

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = stream.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
